package com.red.wood.module.cdn.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.red.wood.common.domain.Page;
import com.red.wood.common.util.CommonUtils;
import com.red.wood.common.util.ExportExcelUtil;
import com.red.wood.common.util.IMap;
import com.red.wood.module.cdn.mybatis.service.CdnDataService;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/cdnData")
public class CdnDataController{
	
	private static final Log log = LogFactory.getLog(CdnDataController.class);
	
	@Autowired
	private CdnDataService service;
	/**
	 * CDN首页
	 * 初级权限：企业是本省的及对应企业为本省的资源信息
	 * 中级权限：企业是本省的及对应企业所有的资源，包含该企业的外省资源信息
	 * 高级权限：中级权限+机房是本省的及对应企业是外省下的本省资源
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("cdnDataInfo");
		
		//Enumeration<?> headerNames = request.getHeaderNames();
	    //客户机通过这个头告诉服务器，它是从哪个资源来访问服务器的,直接通过URL访问没有Referer属性
		String referer = request.getHeader("Referer");
		if(StringUtils.isBlank(referer)) {
			mv = new ModelAndView("error");
			return mv;
		}
		String userId = CommonUtils.valueOf(request.getParameter("userId"));
		//loginUser userLevel:1初级，2中级，3高级
		String loginUser = CommonUtils.valueOf(request.getParameter("loginUser"));
		String userLevel = CommonUtils.valueOf(request.getParameter("userLevel"));
		mv.addObject("loginUser",loginUser);
		mv.addObject("userLevel",userLevel);
		mv.addObject("userId",userId);
		log.info("当前传入的用户userId:"+userId);
		log.info("当前传入的用户userLevel:"+userLevel);
		return mv;
	}
	
	/**
	 * CDN数据
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "getCdnDataInfo", method = RequestMethod.POST)
	@ResponseBody
	public String getCdnDataInfo(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		try {
			IMap param = new IMap(request);
			int pageSize = Integer.parseInt(CommonUtils.valueOf(request.getParameter("pageSize")));
			String currentPage = CommonUtils.valueOf(request.getParameter("currentPage"));
			if(StringUtils.isBlank(currentPage)) {
				currentPage = "1";
			}
			Page page = Page.newBuilder(Integer.parseInt(currentPage),pageSize,null);  
			param.put("page",page);
			
			Map<String,Object> rs = service.getPageData(param);
			page.setTotalRecord(Integer.parseInt(CommonUtils.valueOf(rs.get("totalCount"))));
			List<Map<String,Object>> list = (List<Map<String, Object>>) rs.get("pageData");
			
			json.put("flag", true);
			json.put("datas",list);
			json.put("totalPages",page.getTotalPage());
			json.put("totalData", page.getTotalRecord());
			json.put("currentPage", currentPage);
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
		}
		return json.toString();
	}
	
	/**
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "getDetailInfo", method = RequestMethod.POST)
	@ResponseBody
	public String getDetailInfo(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		try {
			String cdnId = CommonUtils.valueOf(request.getParameter("cdnId"));
			Map<String,Object> map = service.getDetailInfo(cdnId);
			json.put("flag", true);
			json.put("datas",map);
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
		}
		return json.toString();
	}
	
	/**
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "exportData",method = RequestMethod.POST)
	@ResponseBody
	public String exportData(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		try {
			IMap param = new IMap(request);
			List<Map<String,Object>> list = service.exportData(param);
			String title = "持证企业";
			String fileName = "cdn_data_";
			String[] columnNames = {"企业名称(简称)","许可证号","企业加速子网数量","企业加速IP段数量","企业客户数量","加速域名数量","机房数量","企业节点数量","企业联系人","联系人电话"};
			String[] mapKey = {"cdnName","cdnId","subNum","ipNum","customerNum","domainNum","houseNum","nodeNum","contacts","contactsPhone"};
			String[] columnsWidth = {"0:40","1:30"}; //列宽特殊处理,0列40字节
			ExportExcelUtil util = new ExportExcelUtil();
			String path = CommonUtils.getDataTempPath() + fileName + System.currentTimeMillis() + ".xlsx";
			util.exportExcel(title, columnNames,columnsWidth, mapKey,list, new FileOutputStream(path), ExportExcelUtil.EXCEl_FILE_2007);
			json.put("flag", true);
			json.put("path",path);
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
		}
		return json.toString();
	}
	
	@RequestMapping(value = "downFiles")
	public String downFiles(HttpServletRequest request, HttpServletResponse response) {
		FileInputStream fs = null;
		OutputStream os = null;
		try {
			String path = request.getParameter("path");
			response.setCharacterEncoding("utf-8");
			response.setHeader("content-disposition","attachment; filename=" + path.substring(path.lastIndexOf(File.separator) + 1, path.length()));
			fs = new FileInputStream(path);
			os = response.getOutputStream();
			int len = 0;
			byte[] b = new byte[1024];
			while ((len = fs.read(b)) != -1) {
				os.write(b, 0, len);
			}
		} catch (Exception e) {
			if(log.isErrorEnabled()) {
				log.error(e.getMessage(),e);
			}
		} finally {
			if (fs != null) {
				try {
					fs.close();
				} catch (IOException e) {
					if(log.isErrorEnabled()) {
						log.error(e.getMessage(),e);
					}
				}
			}
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					if(log.isErrorEnabled()) {
						log.error(e.getMessage(),e);
					}
				}
			}
		}
		return null;
	}
}
